package gdufs.lkl.calculator;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class FunctionStorage {

    private static final String FILE_NAME = "custom_functions.json";
    private final File file;
    private final Gson gson = new Gson();

    public FunctionStorage(Context context) {
        this.file = new File(context.getFilesDir(), FILE_NAME);
    }

    public List<CustomFunction> getFunctions() {
        if (!file.exists()) {
            return new ArrayList<>();
        }
        try (FileReader reader = new FileReader(file)) {
            Type listType = new TypeToken<ArrayList<CustomFunction>>() {}.getType();
            List<CustomFunction> functions = gson.fromJson(reader, listType);
            return functions != null ? functions : new ArrayList<>();
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public void saveFunctions(List<CustomFunction> functions) {
        try (FileWriter writer = new FileWriter(file)) {
            gson.toJson(functions, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addFunction(CustomFunction function) {
        List<CustomFunction> functions = getFunctions();
        functions.add(function);
        saveFunctions(functions);
    }

    public void updateFunction(CustomFunction function) {
        List<CustomFunction> functions = getFunctions();
        for (int i = 0; i < functions.size(); i++) {
            if (functions.get(i).getId() == function.getId()) {
                functions.set(i, function);
                break;
            }
        }
        saveFunctions(functions);
    }

    public void deleteFunction(long functionId) {
        List<CustomFunction> functions = getFunctions();
        functions.removeIf(f -> f.getId() == functionId);
        saveFunctions(functions);
    }
}
